<?php
/**
 * Created by PhpStorm.
 * User: July
 * Date: 2019/3/13
 * Time: 9:39
 *
 * 微信卡券
 */

namespace app\controllers;
use app\models\CouponForm;
use app\models\Msg;
use Yii;
use app\controllers\CommonController;
use yii\data\ActiveDataProvider;
use yii\filters\VerbFilter;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use WxErrcode2Msg;
use linslin\yii2\curl;
use yii\web\Response;


class CouponController extends CommonController
{
    //卡券类型
    public static $card_type_list = array(
        'DISCOUNT' => '折扣券',
        'GROUPON' => '团购券',
        'CASH' => '代金券',
        'GIFT' => '兑换券',
        'GENERAL_COUPON' => '优惠券',
    );
    //卡券码型
    public static $code_type_list = array(
        'CODE_TYPE_QRCODE' => '二维码',
        'CODE_TYPE_BARCODE' => '一维码',
        'CODE_TYPE_ONLY_QRCODE' => '二维码不显示code',
        'CODE_TYPE_TEXT' => '只显示code',
        'CODE_TYPE_NONE' => '无code码',
    );

    //接口地址
    public static $url = array(
        'create_coupon_url'      => 'https://api.weixin.qq.com/card/create?access_token=',  //创建卡券地址
        'get_apply_stores_url'   => 'http://weixiu.sunits.com/index.php/WxcardApi/getServiceList', //获取适用网点接口地址
        'get_apply_goods_url'    => 'http://weixiu.sunits.com/index.php/WxcardApi/getGoodsList',   //获取适用的商品的接口地址
        'update_coupon_url'      => 'https://api.weixin.qq.com/card/update?access_token=',  //更新卡券接口地址
        'get_card_info_url'      => 'https://api.weixin.qq.com/card/get?access_token=',     //获取卡券信息接口地址
        'send_card_msg_url'      => 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=', //发送卡券消息地址
        'card_qrcode_url'        => 'https://api.weixin.qq.com/card/qrcode/create?access_token=',    //卡券二维码投放接口地址
        'qrcode_ticket_url'      => 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=',           //生成卡券二维码获取ticket地址
        'user_card_list_url'     => 'https://api.weixin.qq.com/card/user/getcardlist?access_token=', //获取用户卡券列表的url',
        'delete_card_url'        => 'https://api.weixin.qq.com/card/delete?access_token=',           //删除卡券接口地址
        'decrypt_code_url'       => 'https://api.weixin.qq.com/card/code/decrypt?access_token=',     //卡券code解密接口地址
        'unavailable__card_url'  => 'https://api.weixin.qq.com/card/code/unavailable?access_token=', //设置卡券失效接口地址
        'consume_code_url'       => 'https://api.weixin.qq.com/card/code/consume?access_token=', //核销地址
    );

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 卡券列表
     * @return string
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => CouponForm::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * 发送卡券消息列表
     */
    public function actionMsgList()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Msg::find(),
        ]);

        return $this->render('msg-list', [
            'dataProvider' => $dataProvider,
        ]);
    }


    /**
     * 创建卡券:共5种类型卡券:团购券、代金券、折扣券、兑换券、优惠券
     * @return string
     * @throws \yii\db\Exception
     */
    public function actionCreate()
    {
        $couponModel = new CouponForm();
        if ($couponModel->load(Yii::$app->request->post())) {
            //创建卡券地址
            $create_coupon_url = self::$url['create_coupon_url'];
            //获取access_token
            $access_token = $this->get_access_token();

            $request = \Yii::$app->request;
            $request_data = $request->post();
            $data = $request_data['CouponForm'];
            //处理数据，将提交回来的数据处理成符合微信的数据，添加、编辑都需要用到，提取出来
            $coupon_data = $this->handleCouponData('create', $data);
            //请求微信卡券接口创建卡券
            $card_result = $this->curlpostJson($create_coupon_url . $access_token, $coupon_data, true);
            //将创建成功的卡券存入表
            if ($card_result['errcode'] == 0) {
                //处理form表单数据，写入本地数据库
                $insertData = $this->handleInsertData($data);
                $insertData = array_merge($insertData, array('card_id'=>$card_result['card_id']));
                Yii::$app->db->createCommand()->insert('wx_card', $insertData)->execute();
                Yii::$app->getSession()->setFlash('success', '添加成功');
                return $this->redirect(['index']);
            } else {
                $msg = WxErrcode2Msg::errCoode2Msg($card_result['errcode']);
                Yii::$app->getSession()->setFlash('error', '添加失败，'.$msg);
                return $this->goBack();
            }
        }
        //发放配置
        //1、默认选中线上
        $couponModel->business_type = 1;
        return $this->render('create', [
            'model' => $couponModel,
            'card_type_list' => self::$card_type_list,  //卡券类型
            'code_type_list' => self::$code_type_list,  //卡券码型
            'color_list' => $this->getCardColors(),
        ]);
    }

    public function actionGetapplystores(){
        return $this->render('selectstores');
    }
    //获取适用网点列表
    public function actionAjaxgetapplystores(){
        $curl = new curl\Curl();
        $get_apply_stores_url = self::$url['get_apply_stores_url'];
        $data = $curl->get($get_apply_stores_url);
        Yii::$app->response->format = Response::FORMAT_JSON;
        if($curl->errorCode !== null){
            $result = array('code'=>-1);
        }else{
            $storesListArr = json_decode($data, true);
            if($storesListArr['code'] != 0){
                $result = array('code'=>-1);
            }else{
                $storeslist = $storesListArr['data'];
                $result = array('code'=>0, 'data'=>$storeslist);
            }
        }
        return $result;
    }

    /**
     * @return string
     */
    public function actionGetapplygoods(){
        return $this->render('selectgoods');
    }
    //获取适用商品
    public function actionAjaxgetapplygoods(){
        $curl = new curl\Curl();
        $get_apply_goods_url = self::$url['get_apply_goods_url'];
        $data = $curl->get($get_apply_goods_url);
        Yii::$app->response->format = Response::FORMAT_JSON;
        if($curl->errorCode !== null){
            $result = array('code'=>-1);
        }else{
            $goodsListArr = json_decode($data, true);
            if($goodsListArr['code'] != 0){
                $result = array('code'=>-1);
            }else{
                $goodslist = $goodsListArr['data'];
                $result = array('code'=>0, 'data'=>$goodslist);
            }
        }
        return $result;
    }

    //卡券颜色
    public function getCardColors()
    {
        return array(
            'Color010' => '#63b359', 'Color020' => '#2c9f67', 'Color030' => '#509fc9', 'Color040' => '#5885cf', 'Color050' => '#9062c0',
            'Color060' => '#d09a45', 'Color070' => '#e4b138', 'Color080' => '#ee903c', 'Color081' => '#f08500', 'Color082' => '#a9d92d',
            'Color090' => '#dd6549', 'Color100' => '#cc463d', 'Color101' => '#cf3e36', 'Color102' => '#5E6671',
        );
    }

    //卡券颜色转换  HEX格式转化为微信的卡券颜色
    public function HEX2wxcolor($hex_color)
    {
        $colorsArr = $this->getCardColors();
        $hex_colors = array_values($colorsArr);
        $wx_colors = array_keys($colorsArr);
        if (!in_array($hex_color, $hex_colors)) {
            return '';
        }
        $key = array_search($hex_color, $hex_colors);
        $wx_color = $wx_colors[$key];
        return $wx_color;
    }

    //处理卡券的字段，把前段提交回来的数据处理成符合微信的数据
    public function handleCouponData($action, $data)
    {
        if ($action === 'create') {
            //卡券类型
            $card_type = $data['card_type'];
            //卡券使用期限，有效期
            if ($data['date_type'] == 'DATE_TYPE_FIX_TERM') {//自领取多长时间内可使用
                $data_info = array(
                    'type' => 'DATE_TYPE_FIX_TERM',
                    'fixed_term' => $data['fixed_term'],      //领取后多少天内有效
                    'fixed_begin_term' => $data['fixed_begin_term'] ? $data['fixed_begin_term'] : 0, //自领取后多少天开始生效，当天生效填写0
                    'end_timestamp' => strtotime($data['end_timestamp']),    //卡券过期时间，可以不填
                );
            } elseif ($data['date_type'] == 'DATE_TYPE_FIX_TIME_RANGE') { //固定日期区间使用
                $data_info = array(
                    'type' => 'DATE_TYPE_FIX_TIME_RANGE',
                    'begin_timestamp' => strtotime($data['begin_timestamp']),    //卡券起用时间，必填
                    'end_timestamp' => strtotime($data['end_timestamp']),      //卡券过期时间，非必填
                );
            }
            //卡券基础信息
            $base_info = array(
                /*------------必填字段 start-----------*/
                'logo_url' => $data['logo_url'],   //卡券的商户logo，建议像素为300*300
                'code_type' => $data['code_type'],  //卡券码型
                'brand_name' => $data['brand_name'], //商户名称，最多12个汉字
                'title' => $data['title'],      //卡券名称，最多9个汉字 例如：双人套餐100元兑换券
                'color' => $data['color'],      //卡券颜色，查看文档填写，不能自定义
                'notice' => $data['notice'],     //卡券使用提醒，最多16个汉字
                'description' => $data['description'],//卡券使用说明，最多1024个汉字
                'sku' => array(
                    'quantity' => $data['quantity']  //卡券库存的数量，最多为1亿
                ),
                'date_info' => $data_info,          //卡券的使用日期，有效期的信息
                /*------------必填字段  end-----------*/

                /*------------非必填字段 start-----------*/
                'use_custom_code' => false,  //是否自定义code，默认false
                'get_custom_code_mode' => '',   //表示该卡券为预存code模式卡券,先导入自定义code，quantity字段须为0,须导入code 后再增加库存
                'bind_openid' => false, //是否指定用户领取，true指定用户，默认false
                'service_phone' => $data['service_phone'] ? $data['service_phone'] : '',   //客服电话
                //'location_id_list'      => $location_id_listArr ? $location_id_listArr : '', //数组格式，门店位置poiid,线下门店必填
                //'use_all_locations'     => $data['use_all_locations'] === false ? false : true, //是否支持全部门店
                'center_title' => $data['center_title'] ? $data['center_title'] : '',  //卡券顶部居中的按钮文字信息
                'center_sub_title' => $data['center_sub_title'] ? $data['center_sub_title'] : '', //显示在入口下方的提示语
                'center_url' => $data['center_url'] ? $data['center_url'] : '', //顶部居中的url
                //'center_app_brand_user_name' => $data['center_app_brand_user_name'] ? $data['center_app_brand_user_name'] : '',//卡券跳转的小程序的user_name
                //'center_app_brand_pass' => $data['center_app_brand_pass'] ? $data['center_app_brand_pass'] : '', //卡券跳转的小程序的path
                'custom_url_name' => $data['custom_url_name'] ? $data['custom_url_name'] : '', //自定义跳转外链的入口名字
                'custom_url' => $data['custom_url'] ? $data['custom_url'] : '',  //自定义跳转的url
                'custom_url_sub_title' => $data['custom_url_sub_title'] ? $data['custom_url_sub_title'] : '', //显示在入口右侧的提示语
                //'custom_app_brand_user_name' => $data['custom_app_brand_user_name'] ? $data['custom_app_brand_user_name'] : '', //卡券跳转的小程序的user_name
                //'custom_app_brand_pass'=> $data['custom_app_brand_pass'] ? $data['custom_app_brand_pass'] : '', //卡券跳转的小程序的path
                'promotion_url_name' => $data['promotion_url_name'] ? $data['promotion_url_name'] : '', //营销场景的自定义入口名称
                'promotion_url' => $data['promotion_url'] ? $data['promotion_url'] : '', //入口跳转外链的地址链接
                'promotion_url_sub_title' => $data['promotion_url_sub_title'] ? $data['promotion_url_sub_title'] : '', //显示在营销入口右侧的提示语
                //'promotion_app_brand_user_name' => $data['promotion_app_brand_user_name'] ? $data['promotion_app_brand_user_name'] : '',//卡券跳转的小程序的user_name
                //'promotion_app_brand_pass'      => $data['promotion_app_brand_pass'] ? $data['promotion_app_brand_pass'] : '', //卡券跳转的小程序的path
                'get_limit' => $data['get_limit'] ? $data['get_limit'] : 50,  //每人可领的券的数量，默认50
                'use_limit' => $data['use_limit'] ? $data['use_limit'] : 50,  //每人可核销的券的数量，默认50
                'can_share' => $data['can_share'] == 1 ? true : false,     //领券页面是否可以分享
                'can_give_friend' => $data['can_give_friend'] == 1 ? true : false, //是否可转赠
                /*------------非必填字段 end-----------*/
            );
            //处理数组,得到新的$base_info
            $base_info = $this->array_filter_recursive($base_info);
            //团购券
            if ($card_type === 'GROUPON') {
                $coupon_data = array(
                    'card' => array(
                        'card_type' => $card_type,
                        'groupon' => array(
                            'base_info' => $base_info,
//                        'advanced_info' => $advanced_info,
                            'deal_detail' => $data['deal_detail']//团购券专用，团购详情。
                        )
                    )
                );
            } //代金券
            elseif ($card_type === 'CASH') {
                $coupon_data = array(
                    'card' => array(
                        'card_type' => $card_type,
                        'cash' => array(
                            'base_info' => $base_info,
//                        'advanced_info' => $advanced_info,
                            'least_cost' => $data['least_cost'],//代金券专用，表示起用金额（单位为分）,如果无起用门槛则填0。
                            'reduce_cost' => $data['reduce_cost']//代金券专用，表示减免金额。（单位为分）
                        )
                    )
                );
            } //折扣券
            elseif ($card_type === 'DISCOUNT') {
                $coupon_data = array(
                    'card' => array(
                        'card_type' => $card_type,
                        'discount' => array(
                            'base_info' => $base_info,
//                        'advanced_info' => $advanced_info,
                            'discount' => $data['discount']//折扣券专用，表示打折额度（百分比）。填30就是七折。
                        )
                    )
                );
            } //兑换券
            elseif ($card_type === 'GIFT') {
                $coupon_data = array(
                    'card' => array(
                        'card_type' => $card_type,
                        'gift' => array(
                            'base_info' => $base_info,
//                        'advanced_info' => $advanced_info,
                            'gift' => $data['gift']//兑换券专用，填写兑换内容的名称。
                        )
                    )
                );
            } //优惠券
            elseif ($card_type === 'GENERAL_COUPON') {
                $coupon_data = array(
                    'card' => array(
                        'card_type' => $card_type,
                        'general_coupon' => array(
                            'base_info' => $base_info,
//                        'advanced_info' => $advanced_info,
                            'default_detail' => $data['default_detail']//优惠券专用，填写优惠详情。
                        )
                    )
                );
            }
        } elseif ($action === 'update') {
            //整理编辑数据
            $card_type = $data['card_type'];
            $base_info = array(
                'logo_url' => $data['logo_url'] ? $data['logo_url'] : '',
                'code_type' => $data['code_type'] ? $data['code_type'] : '',
                'color' => $data['color'] ? $data['color'] : '',
                'notice' => $data['notice'] ? $data['notice'] : '',
                'description' => $data['description'] ? $data['description'] : '',
                'get_limit' => $data['get_limit'] ? $data['get_limit'] : 50,
                'use_limit' => $data['use_limit'] ? $data['use_limit'] : 50,
                'service_phone' => $data['service_phone'] ? $data['service_phone'] : '',
                'can_share' => $data['can_share'] == 1 ? true : false,
                'can_give_friend' => $data['can_give_friend'] == 1 ? true : false,
                'center_title' => $data['center_title'] ? $data['center_title'] : '',
                'center_sub_title' => $data['center_sub_title'] ? $data['center_sub_title'] : '',
                'center_url' => $data['center_url'] ? $data['center_url'] : '',
                'custom_url_name' => $data['custom_url_name'] ? $data['custom_url_name'] : '',
                'custom_url_sub_title' => $data['custom_url_sub_title'] ? $data['custom_url_sub_title'] : '',
                'custom_url' => $data['custom_url'] ? $data['custom_url'] : '',
                'promotion_url_name' => $data['promotion_url_name'] ? $data['promotion_url_name'] : '',
                'promotion_url_sub_title' => $data['promotion_url_sub_title'] ? $data['promotion_url_sub_title'] : '',
                'promotion_url' => $data['promotion_url'] ? $data['promotion_url'] : '',
            );
            $date_type = $data['date_type'];
            if($date_type == 'DATE_TYPE_FIX_TERM'){
                //更新卡券时不支持该类型，去掉
                unset($data['date_type']);
                unset($data['end_timestamp']);
            }elseif($date_type == 'DATE_TYPE_FIX_TIME_RANGE'){
                $date_info = array(
                    'type'       => 'DATE_TYPE_FIX_TIME_RANGE',
                    'begin_timestamp' => strtotime($data['begin_timestamp']),
                    'end_timestamp'   => strtotime($data['end_timestamp']),
                );
                $base_info = array_merge($base_info, array('date_info'=>$date_info));
            }
            $base_info = $this->array_filter_recursive($base_info);
            $coupon_data = array(
                'card_id' => $data['card_id'],
                strtolower($card_type) => array(
                    'base_info' => $base_info,
                ),
            );
        }
        return $coupon_data;
    }

    /**
     * 处理数据，写入本地数据库
     * @param array $data
     * @return array
     */
    public function handleInsertData($data = array()){
        if(empty($data)){
            return array();
        }
        $intfields = array('least_cost', 'reduce_cost', 'fixed_term', 'fixed_begin_term', 'begin_timestamp', 'end_timestamp');
        foreach ($data as $k => $v) {
            if(in_array($k, $intfields)){
                if(!$v){
                    $data[$k] = 0;
                }
            }
        }
        return $data;
    }

    /**
     * 卡券详情
     * @param $id
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function findModel($id)
    {
        if (($model = CouponForm::findOne($id)) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('The requested page does not exist.');
    }

    //卡券编辑页面
    public function actionUpdate()
    {
        $id = Yii::$app->request->get('id', 0);
        if (!$id || !is_numeric($id)) {
            return $this->redirect(['coupon/index']);
        }
        $dbcardinfo = $this->getdbcardinfo($id);
        if (empty($dbcardinfo)) {
            return $this->redirect(['coupon/index']);
        }
        $couponModel = $this->findModel($id);
        if ($couponModel->load(Yii::$app->request->post())) {
            //更新卡券接口地址
            $update_coupon_url = self::$url['update_coupon_url'];
            //获取access_token
            $access_token = $this->get_access_token();

            $request = \Yii::$app->request;
            $request_data = $request->post();
            $data = $request_data['CouponForm'];
            $data['card_id'] = $dbcardinfo['card_id'];
            //处理数据，将提交回来的数据处理成符合微信的数据，添加、编辑都需要用到，提取出来
            $coupon_data = $this->handleCouponData('update', $data);
            //请求微信卡券接口更新卡券
            $card_result = $this->curlpostJson($update_coupon_url . $access_token, $coupon_data, true);
            //将创建成功的卡券存入表
            if ($card_result['errcode'] == 0) {
                //更新
                $card_name = $data['card_name'];
                Yii::$app->db->createCommand('UPDATE wx_card SET `card_name` = "' . $card_name . '" where id = ' . $id)->execute();
                Yii::$app->getSession()->setFlash('success', '更新成功');
                return $this->redirect(['index']);
            } else {
                $msg = WxErrcode2Msg::errCoode2Msg($card_result['errcode']);
                Yii::$app->getSession()->setFlash('error', '更新失败,'.$msg);
                return $this->goBack();
            }
        }
        $cardInfo = $this->getCardInfoByCardId($dbcardinfo['card_id']);
        if (empty($cardInfo)) {
            return $this->redirect(['coupon/index']);
        }

        //卡券名称
        $cardInfo['card_name'] = $dbcardinfo['card_name'];
        $cardInfo['business_type'] = $dbcardinfo['business_type'];
        $cardInfo['apply_stores'] = $dbcardinfo['apply_stores'];
        $cardInfo['apply_goods'] = $dbcardinfo['apply_goods'];
        //把cardInfo的值赋值给$couponModel
        $couponModel = $this->assigncouponModel($couponModel, $cardInfo);

        $card_typeName = self::$card_type_list[$couponModel->card_type];
        return $this->render('update', [
            'model' => $couponModel,
            'code_type_list' => self::$code_type_list,
            'code_typeName' => $card_typeName,
            'color_list' => $this->getCardColors(),
        ]);
    }

    //编辑卡券时给对象赋值
    public function assigncouponModel($couponModel, $cardInfo)
    {
        //自定义字段  start
        $couponModel->card_name = $cardInfo['card_name'];
        $couponModel->business_type = $cardInfo['business_type'];
        $couponModel->apply_stores = $cardInfo['apply_stores'];
        $couponModel->apply_goods = $cardInfo['apply_goods'];
        //自定义字段  end
        $card_type = $cardInfo['card_type'];
        $couponModel->card_type = $card_type;
        $card_data = $cardInfo[strtolower($card_type)];
        $couponModel->logo_url = $card_data['base_info']['logo_url'];
        $couponModel->brand_name = $card_data['base_info']['brand_name'];
        $couponModel->code_type = $card_data['base_info']['code_type'];
        $couponModel->color = $this->HEX2wxcolor($card_data['base_info']['color']);
        $couponModel->notice = isset($card_data['base_info']['notice']) ? $card_data['base_info']['notice'] : '';
        $couponModel->description = isset($card_data['base_info']['description']) ? $card_data['base_info']['description'] : '';
        $couponModel->date_type  = $card_data['base_info']['date_info']['type'];  //使用时间类型
        if($couponModel->date_type == 'DATE_TYPE_FIX_TERM'){
            $couponModel->end_timestamp = date('Y-m-d', $card_data['base_info']['date_info']['end_timestamp']);       //卡券过期时间，非必填
        }elseif($couponModel->date_type == 'DATE_TYPE_FIX_TIME_RANGE'){
            //如果使用日期是范围格式的，则显示当前的启用时间和过期时间
            $couponModel->begin_timestamp = date('Y-m-d', $card_data['base_info']['date_info']['begin_timestamp']);   //卡券起用时间，必填
            $couponModel->end_timestamp = date('Y-m-d', $card_data['base_info']['date_info']['end_timestamp']);       //卡券过期时间，非必填
        }
        $couponModel->get_limit = isset($card_data['base_info']['get_limit']) ? $card_data['base_info']['get_limit'] : 50;
        $couponModel->use_limit = isset($card_data['base_info']['use_limit']) ? $card_data['base_info']['use_limit'] : 50;
        $couponModel->service_phone = isset($card_data['base_info']['service_phone']) ? $card_data['base_info']['service_phone'] : '';
        $couponModel->can_share = $card_data['base_info']['can_share'] === true ? 1 : 0;
        $couponModel->can_give_friend = $card_data['base_info']['can_give_friend'] === true ? 1 : 0;
        $couponModel->center_title = isset($card_data['base_info']['center_title']) ? $card_data['base_info']['center_title'] : '';
        $couponModel->center_sub_title = isset($card_data['base_info']['center_sub_title']) ? $card_data['base_info']['center_sub_title'] : '';
        $couponModel->center_url = isset($card_data['base_info']['center_url']) ? $card_data['base_info']['center_url'] : '';
        $couponModel->custom_url_name = isset($card_data['base_info']['custom_url_name']) ? $card_data['base_info']['custom_url_name'] : '';
        $couponModel->custom_url_sub_title = isset($card_data['base_info']['custom_url_sub_title']) ? $card_data['base_info']['custom_url_sub_title'] : '';
        $couponModel->custom_url = isset($card_data['base_info']['custom_url']) ? $card_data['base_info']['custom_url'] : '';
        $couponModel->promotion_url_name = isset($card_data['base_info']['promotion_url_name']) ? $card_data['base_info']['promotion_url_name'] : '';
        $couponModel->promotion_url_sub_title = isset($card_data['base_info']['promotion_url_sub_title']) ? $card_data['base_info']['promotion_url_sub_title'] : '';
        $couponModel->promotion_url = isset($card_data['base_info']['promotion_url']) ? $card_data['base_info']['promotion_url'] : '';
        return $couponModel;
    }

    //获取card_id
    public function getdbcardinfo($id)
    {
        $card_id = Yii::$app->db->createCommand('select * from `wx_card` where `id` = ' . $id)->queryOne();
        return $card_id ? $card_id : array();
    }

    //获取卡券信息
    public function getCardInfoByCardId($card_id)
    {
        $getCardUrl = self::$url['get_card_info_url'];
        $access_token = $this->get_access_token();
        $data = array(
            'card_id' => $card_id
        );
        $cardInfo_Arr = $this->curlpostJson($getCardUrl . $access_token, $data, true); //post请求
        if ($cardInfo_Arr['errcode'] != 0) {
            //未获取到
            return array();
        } else {
            return $cardInfo_Arr['card'];
        }
    }

    /**
     * 发送卡券消息，用户点击领取
     */
    public function actionMsg($id)
    {
        $couponModel = new CouponForm();
        if ($couponModel->load(Yii::$app->request->post())) {
            //发送消息地址
            $sendmsg_url = self::$url['send_card_msg_url'];
            $access_token = $this->get_access_token();
            $request = \Yii::$app->request;
            $data = $request->post();
            $openid = $data['CouponForm']['openid'];
            $card_info = CouponForm::findOne($id)->toArray();
            $card_id = $card_info['card_id'];
            $postcardData = array(
                'touser' => $openid,
                'msgtype' => 'wxcard',
                'wxcard' => array(
                    'card_id' => $card_id
                )
            );
            $isSendcardMsg = $this->curlpostJson($sendmsg_url . $access_token, $postcardData, true);
            if ($isSendcardMsg['errcode'] == 0) {
                Yii::$app->db->createCommand()->insert('wx_cardmsg', [
                    'touser' => $openid,
                    'card_id' => $card_id,
                    'send_time' => time()
                ])->execute();
                Yii::$app->getSession()->setFlash('success', '发送成功');
                return $this->redirect(['index']);
            }else{
                $msg = WxErrcode2Msg::errCoode2Msg($isSendcardMsg['errcode']);
                Yii::$app->getSession()->setFlash('error', '发送失败，'.$msg);
                return $this->redirect(['index']);
            }
        }
        return $this->render('msg', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * 二维码投放卡券
     */
    public function actionCode($id)
    {
        $card_info = CouponForm::findOne($id)->toArray();
        //创建二维码地址
        $qrCodeUrl = self::$url['card_qrcode_url'];
        $access_token = $this->get_access_token();
        $data = array(
            'action_name' => 'QR_CARD',
            'expire_seconds' => 1800,
            'action_info' => array(
                'card' => array(
                    'card_id' => $card_info['card_id'],
                    'code' => '',
                    'openid' => '',
                    'is_unique_code' => false,
                    'outer_id' => ''
                )
            )
        );
        $result = $this->curlpostJson($qrCodeUrl . $access_token, $data, true);
        if ($result['errcode'] == 0) {
            $ticketUrl = self::$url['qrcode_ticket_url'];
            $ticket = $result['ticket'];
            $qrCodeUrl = $ticketUrl . urlencode($ticket);
        }else{
            $msg = WxErrcode2Msg::errCoode2Msg($result['errcode']);
            Yii::$app->getSession()->setFlash('error', '二维码生成失败，'.$msg);
            return $this->redirect(['coupon/index']);
        }

        return $this->render('code', [
            'model' => $this->findModel($id),
            'qr_url' => $qrCodeUrl
        ]);
    }

    /**
     * 获取用户已领取的卡券列表
     */
    public function actionUsercardlist()
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $user_cardlist_url = self::$url['user_card_list_url']; //获取用户卡券列表的url
        $access_token = $this->get_access_token();
        $request = \Yii::$app->request;
        $data = $request->get();
        if(isset($data['openid'])){
            $openid = $data['openid'];
        }else{
            $openid = '';
        }
        if(isset($data['card_id'])){
            $card_id = $data['card_id'];
        }else{
            $card_id = '';
        }
        if(!$openid){
            return array('code'=>-1, 'msg'=>'openid参数不能为空');
        }
        $postcardlistData = array(
            'openid' => $openid,
            'card_id' => $card_id
        );
        $usercardlist = $this->curlpostJson($user_cardlist_url . $access_token, $postcardlistData, true);
        if ($usercardlist['errcode'] == 0) {
            return [
                'code' => 0,
                'msg'  => '获取成功',
                'data' => [
                    'card_list'=>$usercardlist['card_list'],
                    'has_share_card'=>$usercardlist['has_share_card']
                ]
            ];
        }else{
            $msg = WxErrcode2Msg::errCoode2Msg($usercardlist['errcode']);
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return [
                'code' => $usercardlist['errcode'],
                'msg'  => $msg,
            ];
        }
    }

    /**
     * 删除卡券
     */
    public function actionDelete($id)
    {
        $card_info = CouponForm::findOne($id)->toArray();
        //调用微信接口删除微信卡券
        $delete_url = self::$url['delete_card_url'];
        $access_token = $this->get_access_token();
        $postData = array(
            'card_id' => $card_info['card_id']
        );
        $result = $this->curlpostJson($delete_url . $access_token, $postData, true);
        if ($result['errcode'] == 0) {
            //删除数据库中的卡券
            $this->findModel($id)->delete();
            Yii::$app->getSession()->setFlash('success', '删除成功');
        }else{
            $msg = WxErrcode2Msg::errCoode2Msg($result['errcode']);
            Yii::$app->getSession()->setFlash('error', '删除失败，'.$msg);
        }
        return $this->redirect(['index']);
    }


    /**
     * 卡券code码解密(通过卡券自定义外链进入其他页面后解码真实code)
     */
    public function actionDecrypt()
    {
        $decrypt_url = self::$url['decrypt_code_url'];
        $access_token = $this->get_access_token();
        $request = \Yii::$app->request;
        $encrypt_code = $request->get('encrypt_code');
        $postData = array(
            'encrypt_code' => $encrypt_code
        );
        $true_codeArr = $this->curlpostJson($decrypt_url . $access_token, $postData, true);
        if ($true_codeArr['errcode'] == 0) {
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return [
                'code' => 0,
                'msg'  => 'code解密成功',
                'data' => $true_codeArr['code'],
            ];
        }else{
            $msg = WxErrcode2Msg::errCoode2Msg($true_codeArr['errcode']);
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return [
                'code' => $true_codeArr['errcode'],
                'msg'  => $msg,
            ];
        }
    }

    /**
     * 设置卡券失效
     */
    public function actionInvalidate()
    {
        $couponModel = new CouponForm();
        if ($couponModel->load(Yii::$app->request->post())) {
            $invalidate_url = self::$url['unavailable__card_url'];
            $access_token = $this->get_access_token();
            $request = \Yii::$app->request;
            $data = $request->post();
            $code = $data['CouponForm']['code'];
            $card_id = $data['CouponForm']['card_id'];
            $reason = $data['CouponForm']['reason'];
            $postData = array(
                'card_id' => $card_id,
                'code' => $code,
                'reason' => $reason
            );

            $result = $this->curlpostJson($invalidate_url . $access_token, $postData, true);
            if ($result['errcode'] == 0) {
                return $this->redirect(['index']);
//                \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
//                return [
//                    'statusCode ' => 200,
//                    'message' => 'Success',
//                ];
            }else{
                $msg = WxErrcode2Msg::errCoode2Msg($result['errcode']);
                Yii::$app->getSession()->setFlash('error', '失败，'.$msg);
            }
        }
        return $this->render('invalidate', [
            'model' => $couponModel,
        ]);
    }


}